<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use think\Db;
use wxdecrypt\WXBizDataCrypt;
class Login extends Controller
{
    private $appid="wx49d5ef2a0bda35a4";
    private $appSecret = "39f9b7f0d5cf4df0cfb0a3f7c47accaf";

    //状态码 0成功 100没有携带参数  101请传入用户uid  400上传图片失败
    private $code = [0,100,101,400];
    //登录接口
    public function index()
    {
        $request = Request::instance();//$request中的数据有 code    encryptedData   iv
        if ($request->post('code'))
        {
          //return json("123");
            $data = $this->getOpenid($request->post('code'));//$data中的数据有session_key    expires_in   openid
        
            //检查用户第一次登录
            if(!Db::name('onuser')->where("openid",$data['openid'])->select()){
                 $info = json_decode($this->getUserInfo($data['session_key'],$request->post('encryptedData'),$request->post('iv')),true);//把用户资料解密出来

                if($info){
                   $member=array();

                   $member['province'] = $info['province'];
                   $member['country'] = $info['country'];
                   $member['city'] = $info['city'];
                   $member['uid'] = $this->getuid();

                   $member['username']=$info['nickName'];
                   $member['openid']=$info['openId'];
                   $member['avatar']=$info['avatarUrl'];

        
                   $member['createtime'] =time();
                   $member['logintime'] =time();
                   $member['province'] = $info['province'];
                  
                   
                   $userid = Db::name('onuser')->insertGetId($member);  //添加用户返回用户id

                }
            }

            //更新登陆后用户基础数据
            $mess = Db::name('onuser')->where("openid",$data['openid'])->select()[0];

            if (Db::name('onuser')
                  ->where("openid",$data['openid'])
                  ->update([
                          'prevtime'=>$mess["logintime"],
                          'loginip' => $request->ip(),
                          'logintime' => time()
                  ])
                ){
                $returns = Db::name('onuser')->field('uid,username,avatar,openid')->where("openid",$data['openid'])->select()[0];
                return json(['code'=>($this->code[0]),'msg'=>'登录成功','data'=>$returns]);
            }
            
        }else{
            return json(['code'=>($this->code[1]),'msg'=>'登录失败,没有携带参数','data'=>null]);
        }
    }


    //获取session_key openId
    private function getOpenid($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->appSecret."&js_code=".$code."&grant_type=authorization_code";
        $data = file_get_contents($url);
        $data = json_decode($data,true);
        return $data;
    }
    //通过$session_key $encryptedData ,$vi解密用户信息
    private function getUserInfo($sessionKey,$encryptedData, $iv)
    {
        $pc = new WXBizDataCrypt($this->appid,$sessionKey);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);
        if ($errCode == 0) {
            return $data;
        } else {
            return false;
        }
    }

    //生成16位数
    function getuid() {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }


   
}